package org.example.thread2;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 使用共享变量的方式结束线程
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2020/10/31 13:38
 */
public class InterruptThread2 implements Runnable {
    //线程退出标识共享对象，用对象的目的是方便在外面设置对象的值。
    private Map<String, Boolean> isExist;

    public InterruptThread2(Map<String, Boolean> isExit) {
        this.isExist = isExit;
    }

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10 && !isExist.get("flag"); i++) {
                System.out.println((i) + " = " + Thread.currentThread().getName());
                //随机休眠，模拟此时在进行其它操作
                Thread.currentThread().sleep(200 + new Random().nextInt(1500));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            Map<String, Boolean> isExist = new HashMap<>();
            isExist.put("flag", false);
            InterruptThread2 interruptThread2 = new InterruptThread2(isExist);
            new Thread(interruptThread2).start();
            //5秒后设置推出标识为 true，让子线程推出循环
            TimeUnit.SECONDS.sleep(5);
            isExist.put("flag", true);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
